<?php
class Home extends CI_Controller{
    protected $_gallery_path = "";
    protected $_gallery_url = "";
	public $model_result;
	public $countloop = 0;
    public $mPublicTheLoai = '0';

    public function  __construct() {
        parent::__construct();
		require_once(APPPATH. '/functions/application.php'); 
        $this->load->library("admin_layout"); // Sử dụng thư viện layout
        $this->admin_layout->setLayout("layout/admin"); // load file layout chính (view/layout/frontend.php)
        $this->load->Model("Mtintuc");
        $this->load->Model("M_theloai");
		 $this->load->Model("Mconfig");
        $this->load->helper("text");
    }

    // Controller mặc định cho trang chủ
    public function index(){
        
        $data['title'] = "Danh sách tin tức";
        $config['base_url'] = base_url('admin/tintuc/index/'); // xác định trang phân trang 
        $config['total_rows'] = $this->Mtintuc->count_all(); // xác định tổng số record 
        $configFrontEnd = $this->Mconfig->get_One();
		if($configFrontEnd == NULL)
			$config['per_page'] = 10; // xác định số record ở mỗi trang
		else
			$config['per_page'] = $configFrontEnd->cf_PageSize; // xác định số record ở mỗi trang
        $config['uri_segment'] = 4; // xác định segment chứa page number 
        
       
        $this->pagination->initialize($config); 
        $data['data']=$this->Mtintuc->list_with_page($config['per_page'],$this->uri->segment($config['uri_segment'])); 
        $data['navigation']['title'] = 'Quản lý tin tức';
		$data['navigation']['active']= 'Danh sách tin';
        $this->admin_layout->view("admin/home",$data);
    }
	// Khu vực hàm dành cho Load combobox
	public function CategoriesToTree(&$categories) {

		$map = array(
			0 => array('subcategories' => array())
		);

		foreach ($categories as &$category) {
			$category['subcategories'] = array();
			$map[$category['TheLoai_id']] = &$category;
		}

		foreach ($categories as &$category) {
			$map[$category['Parent_id']]['subcategories'][] = &$category;
		}

		return $map[0]['subcategories'];
	}
	public function ComboboxTree($items, $level = '0')
	{
		$space = str_repeat(' &nbsp &nbsp ', $level);
		foreach ($items as $child=>$value)
		{ 
			//echo '<pre>' . print_r($items[0], true) . '</pre>';	
            
            if($this->mPublicTheLoai != '0' && $this->mPublicTheLoai == $value['TheLoai_id']) {	
    			$this->model_result .= '<option  selected value="'.$value['TheLoai_id'].'">'.$space.$value['TenTheLoai'].'</option>' . "\n";
            } else {
                $this->model_result .= '<option value="'.$value['TheLoai_id'].'">'.$space.$value['TenTheLoai'].'</option>' . "\n";
            }
			if( count($value['subcategories']) > 0)
				$this->ComboboxTree($value['subcategories'],$level+1);
		}
	}
	// Hết khu vực hàm dành cho Load combobox
    public function ThemBaiViet() {
        //var_dump($this->input->post('txtNoiDung', FALSE));
        $data['msg']                  ='';
        $data['navigation']['title']  = 'Quản lý tin tức';
        $data['navigation']['active'] = 'Thêm tin';
        $data['dataListNews']         = $this->Mtintuc->listall();
        $categories                   = $this->M_theloai->get_categories();
        $result                = array();
        
        $convertToArray        = $this->CategoriesToTree($categories);
        $this->model_result    .= $this->ComboboxTree($convertToArray);
        
        $data['combobox_tree'] = $this->model_result;
	
		
        $config = array(
            array(
                 'field' => 'txtTieuDe', 
                 'label' => 'Tiêu Đề', 
                 'rules' => 'required'
            ),
            array(
                 'field' => 'txtGioiThieu', 
                 'label' => 'Giới Thiệu', 
                 'rules' => 'required'
            ),
           
            array(
                 'field' => 'cbChuyenMuc', 
                 'label' => 'Chuyên Mục', 
                 'rules' => 'callback_require_check'
            ),
            array(
                 'field' => 'txtNoiDung', 
                 'label' => 'Nội Dung', 
                 'rules' => 'required'
            ),
           array(
                 'field' => 'txtKeyWord', 
                 'label' => 'Từ Khóa', 
                 'rules' => 'required'
            )
        );
        
        $this->form_validation->set_rules($config);
        $this->form_validation->set_error_delimiters('<div class="error">', '</div>');

        if ($this->form_validation->run() == FALSE) {
			$this->admin_layout->view("admin/ThemBaiViet",$data);
        } else {
            
            $config = array(
                'upload_path'   => 'public/frontend/images/photos',
                'allowed_types' => '*',
                'max_size'      => '2000');

            
            $this->load->library("upload",$config);
            if(!$this->upload->do_upload("fileImage")){
                $arrayErrors= array($this->upload->display_errors());
                $data['msg']  =  "<div class='error'>".$arrayErrors[0]."</div>";
                $this->admin_layout->view("admin/ThemBaiViet",$data);
            }else{
                $image_data = $this->upload->data(); 
                //resize images
                $config = array(
                    "source_image"    => $image_data['full_path'],
                    "new_image"       => "public/frontend/upload",
                    "maintain_ration" => true,
                    "width"           => '140',
                    "height"          => "105"
                );
                $this->load->library("image_lib",$config);
                $this->image_lib->resize();
                $slug = mb_strtolower(url_title(removesign($this->input->post('txtKeyWord'))));  
                // create data
                $data = array(
                    'TieuDe'     => $this->input->post('txtTieuDe'),
                    'TomTat'     => $this->input->post('txtGioiThieu'),
                    'urlHinh'    => $image_data['file_name'],
                    'NoiDung'    => $this->input->post('txtNoiDung',FALSE),
                    'Keywords'   => $this->input->post('txtKeyWord'),
                    'TinNoiBat'  => $this->input->post('radioHotNews'),
                    'AnHien'     => $this->input->post('radioVisible'),
                    'SoLanXem'   => '0',
                    'id_user'    => $this->session->userdata('NguoiDung_id'),
                    'id_TheLoai' => $this->input->post('cbChuyenMuc'),
                    'LastUpdate' => date('m/d/Y h:i:s a', time()+ 7*3600)
                );
                $this -> Mtintuc -> Insert($data);
                redirect('admin/tintuc');
            }
        }

    }

    public function edit($id) {
        
        $data['msg']                  = '<p style="font-weight: bold">Lưu ý: Khi sửa không thành công sẽ load lại dữ liệu cũ.<p>';
        $data['title']                = 'Sửa Tin Tức';
        $data['navigation']['title']  = 'Quản lý tin tức';
        $data['navigation']['active'] = 'Sửa Tin Tức';
        $data['data']                 = $this->Mtintuc->GetTinTuc($id);
        $this->mPublicTheLoai         = $data['data']-> id_TheLoai;        
        $data['dataListNews']         = $this->Mtintuc->listall();
        $categories                   = $this->M_theloai->get_categories();
        $result                       = array();
        $convertToArray               = $this->CategoriesToTree($categories);
        $this->model_result           .= $this->ComboboxTree($convertToArray);
        $data['combobox_tree']        = $this->model_result;


        $config = array(
            array(
                 'field' => 'txtTieuDe', 
                 'label' => 'Tiêu Đề', 
                 'rules' => 'required'
            ),
            array(
                 'field' => 'txtGioiThieu', 
                 'label' => 'Giới Thiệu', 
                 'rules' => 'required'
            ),
           
            array(
                 'field' => 'cbChuyenMuc', 
                 'label' => 'Chuyên Mục', 
                 'rules' => 'callback_require_check'
            ),
            array(
                 'field' => 'txtNoiDung', 
                 'label' => 'Nội Dung', 
                 'rules' => 'required'
            ),
           array(
                 'field' => 'txtKeyWord', 
                 'label' => 'Từ Khóa', 
                 'rules' => 'required'
            )
        );

        $this->form_validation->set_rules($config);
        $this->form_validation->set_error_delimiters('<div class="error">', '</div>');
        if ($this->form_validation->run() == FALSE)
        {
           $this->admin_layout->view("admin/editNews",$data);
        } else {

            if(isset($_REQUEST["save"])) {
                $config = array(
                    'upload_path'   => 'public/frontend/images/photos',
                    'allowed_types' => '*',
                    'max_size'      => '2000');

                
                $this->load->library("upload",$config);
                //$slug = mb_strtolower(url_title(removesign($this->input->post('productKeyWord'))));
                if (empty($_FILES['fileImage']['name'])) {
                    //echo "không file";
                    $data_edit = array(
                        'TieuDe'     => $this->input->post('txtTieuDe'),
                        'TomTat'     => $this->input->post('txtGioiThieu'),
                        'NoiDung'    => $this->input->post('txtNoiDung',FALSE),
                        'Keywords'   => $this->input->post('txtKeyWord'),
                        'TinNoiBat'  => $this->input->post('radioHotNews'),
                        'AnHien'     => $this->input->post('radioVisible'),
                        'id_user'    => $this->session->userdata('NguoiDung_id'),
                        'id_TheLoai' => $this->input->post('cbChuyenMuc'),
                        'LastUpdate' => date('m/d/Y h:i:s a', time()+ 7*3600)
                    );
                    $this -> Mtintuc -> Update($data_edit, $id);
                } else {
                    if(!$this->upload->do_upload("fileImage")){
                        $arrayErrors = array($this->upload->display_errors());
                        $data['msg'] =  "<div class='error'>".$arrayErrors[0]."</div>";
                        $this->admin_layout->view("admin/editNews",$data);
                    }else{
                        $image_data = $this->upload->data();
                        $config = array(
                            "source_image"    => $image_data['full_path'],
                            "new_image"       => "public/frontend/upload",
                            "maintain_ration" => true,
                            "width"           => '140',
                            "height"          => "105"
                        )
                        ;
                        $this->load->library("image_lib",$config);
                        $this->image_lib->resize();

                        $data_edit = array(
                            'TieuDe'     => $this->input->post('txtTieuDe'),
                            'TomTat'     => $this->input->post('txtGioiThieu'),
                            'urlHinh'    => $image_data['file_name'],
                            'NoiDung'    => $this->input->post('txtNoiDung', FALSE),
                            'Keywords'   => $this->input->post('txtKeyWord'),
                            'TinNoiBat'  => $this->input->post('radioHotNews'),
                            'AnHien'     => $this->input->post('radioVisible'),
                            'id_user'    => $this->session->userdata('NguoiDung_id'),
                            'id_TheLoai' => $this->input->post('cbChuyenMuc'),
                            'LastUpdate' => date('m/d/Y h:i:s a', time()+ 7*3600)
                        );
                        
                        $this -> Mtintuc -> Update($data_edit, $id);
                    }

                }
                redirect('admin/tintuc');
            } else {
                $this->admin_layout->view("admin/editNews",$data);
            }
        }
    }

    public function deleteTinTuc() {
        if(isset($_REQUEST["TinTuc_id"])){
            $TinTuc_id   = $_REQUEST["TinTuc_id"];
            $returnValue = $this ->Mtintuc->Delete($TinTuc_id);
            if($returnValue ==1) {
                echo "true";
            } else {
                echo "false";
            }
        }
        
    }

    public function require_check($str){
        if ($str == '0')        {
            $this->form_validation->set_message('require_check', '%s không được trống.');
            return FALSE;
        }
        return TRUE;
    }
}
?>